// 工具类函数集
import CONFIG from "@/config/index.js";
import store from "@/store/index.js";
import guid from "@/uni_modules/uview-ui/libs/function/guid.js";
import {
	openAuthorize
} from "./modules/permissions-handle.js";

import {
	getNowDate
} from "./modules/date-handle.js";
// #ifndef H5
// 支付
export function requestPayment(type, orderInfo) {
	//#ifdef MP-WEIXIN
	return new Promise((resolve, reject) => {
		wx.requestPayment({
			...orderInfo,
			success: res => {
				resolve(res)
			},
			fail: err => {
				reject(err)
			}
		})
	})
	//#endif
	// #ifndef MP-WEIXIN
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			provider: type,
			orderInfo,
			success: res => {
				resolve(res)
			},
			fail: err => {
				reject(err)
			}
		})
	})
	// #endif
}
// #endif

// 加载弹窗
export function showLoading(title) {
	uni.showLoading({
		mask: true,
		title
	})
}

// 提示弹窗
export function toast(title, backFun, duration = 1500, mask = true) {
	uni.showToast({
		title,
		mask,
		icon: "none",
		duration: duration,
		success: () => {
			setTimeout(() => {
				typeof backFun == "function" && backFun()
			}, duration)
		}
	})
}

// 其他弹窗 默认为success
export function oToast(title, backFun, duration = 1500, icon = 'success') {
	uni.showToast({
		title,
		mask: true,
		icon,
		duration: duration,
		success: () => {
			setTimeout(() => {
				typeof backFun == "function" && backFun()
			}, duration)
		}
	})
}

// 上传文件
export function uploadFile(filePath, options, onProgress) {
	const uid = uuid();
	const suffix = options ? options.suffix : "png";
	const {
		url,
		params
	} = store.state.systemConfig.siteConfig.upload
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: url + '?' + uuid(),
			filePath,
			name: 'file',
			header: {
				"Content-Type": "multipart/form-data;",
				"ba-user-token": store.state.vuex_token,
				server: 1
			},
			formData: {
				key: `storage/default/${Object.values(getNowDate()).join("")}/${uid}${Date.now()}${suffix}`,
				token: params.token,
			},
			...options,
			success: (res) => {
				resolve(JSON.parse(res.data));
			},
			fail: (err) => {
				reject(err);
			}
		});
		typeof onProgress == "function" && onProgress(uploadTask);
	})
}

//获取模块内的所有属性
export function getModuleProps(requireModules, fileFormat = 'js') {
	if (Array.isArray(fileFormat)) {
		fileFormat = fileFormat.join("|")
	}
	let obj = {}
	requireModules.keys().forEach((item => {
		const imageRegex = /\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif)$/i;
		const regex = new RegExp(`\/([^\/]+)\.(${fileFormat})$`);
		const match = item.match(regex);
		let fileName = match[1]
		if (imageRegex.test(item)) {
			obj[fileName] = requireModules(item)
		} else {
			obj[fileName] = requireModules(item).default ? requireModules(item).default : requireModules(
				item)
		}
	}))
	return obj
}

export function chooseImage(count = 1, options) {
	return new Promise((resolve, rejects) => {
		// #ifdef MP-WEIXIN
		uni.chooseMedia({
			count,
			mediaType: ['image'],
			...options,
			success: res => {
				let fileList = res.tempFiles.map(item => item.tempFilePath);
				resolve(fileList);
			},
			fail: err => {
				rejects(err);
			}
		})

		// #endif
	})
}

// 获取图片临时路径
export function getImageBlobUrl(url, ...options) {
	return new Promise((resolve, rejects) => {
		uni.getImageInfo({
			src: url,
			success: (res) => {
				resolve(res.path);
			},
			fail: (err) => {
				console.log(err, "下载失败");
				rejects(err);
			}
		})
	});
}

// 保存图片
export function saveImage(filePath) {
	return new Promise((resolve, reject) => {
		uni.saveImageToPhotosAlbum({
			filePath,
			success: res => {
				resolve(res)
			},
			fail: err => {
				reject(err)
			}
		});
	});
}

// 支持保存网络路径图片的方式
export function savePicture(url, authorize = 0) {
	return new Promise(async (resolve, reject) => {
		getImageBlobUrl(url).then(path => {
			saveImage(path).then(res => {
				resolve(res);
			}).catch(error => {
				if (authorize) {
					if (err.errMsg == "saveImageToPhotosAlbum:fail auth deny") {
						openAuthorize('writePhotosAlbum', () => {
							this.saveImage(path);
						});
					} else {
						reject(error);
					}
				} else {
					reject(error);
				}
			});
		}).catch(err => {
			reject(err);
		});
	});
}

// 批量保存图片
export function batchSaveImage(urls) {
	return new Promise(async (resolve, reject) => {
		// #ifdef MP-WEIXIN
		let count = 0;
		const length = urls.length;
		openAuthorize('writePhotosAlbum', (flag) => {
			if (flag) {
				uni.showLoading({
					title: `正在保存图片`,
					mask: true
				});
				for (let i = 0; i < length; i++) {
					let url = urls[i];
					savePicture(url).then(res => {
						count++;
						if (count >= length) {
							uni.hideLoading();
							toast("保存完毕");
							resolve(1);
						}
					});
				}
			} else {
				toast("请重新保存图片");
			}
		});
		// #endif

	});

}

// 分享图片
export function shareImage(path) {
	// #ifdef MP-WEIXIN
	const reg = new RegExp('^(http://|wxfile://)?' + 'tmp')
	if (!reg.test(path)) {
		getImageBlobUrl(path).then(url => {
			// console.log(url, "看看临时路径");
			shareImage(url);
		});
	} else {
		return new Promise((resolve, reject) => {
			wx.showShareImageMenu({
				path,
				success: res => {
					console.log(res, "成功回调");
					resolve(res);
				},
				fail: err => {
					console.log(err, "失败回调");
					reject(err);
				}
			});
		});
	}
	// #endif
}

// 两个版本号比较
export function compareVersion(v1, v2) {
	v1 = v1.split('.')
	v2 = v2.split('.')
	const len = Math.max(v1.length, v2.length)

	while (v1.length < len) {
		v1.push('0')
	}
	while (v2.length < len) {
		v2.push('0')
	}

	for (let i = 0; i < len; i++) {
		const num1 = parseInt(v1[i])
		const num2 = parseInt(v2[i])

		if (num1 > num2) {
			return 1
		} else if (num1 < num2) {
			return -1
		}
	}

	return 0
}

/**
 * 生成全球唯一标识
 * @returns uuid
 */
export function uuid() {
	const hexList = []
	let uuid = '';
	for (let i = 0; i <= 15; i++) {
		hexList[i] = i.toString(16)
	}
	for (let i = 1; i <= 36; i++) {
		if (i === 9 || i === 14 || i === 19 || i === 24) {
			uuid += '-'
		} else if (i === 15) {
			uuid += 4
		} else if (i === 20) {
			uuid += hexList[(Math.random() * 4) | 8]
		} else {
			uuid += hexList[(Math.random() * 16) | 0]
		}
	}
	return uuid
}
// 数组对象去重
export const uniqBy = (array, iteratee) => {
	let iterators = iteratee;
	if (typeof iteratee == "string") {
		iterators = (item) => item[iteratee];
	}
	let filterAfterArr = Array.from(new Set(array.map(iterators)));
	return filterAfterArr.map(val => array.find(item => iterators(item) == val));
}

// 深拷贝
export const deepClone = (obj) => {
	if (obj === null || typeof obj !== 'object') {
		return obj;
	}
	let clone = Array.isArray(obj) ? [] : {};
	for (let key in obj) {
		if (obj.hasOwnProperty(key)) {
			clone[key] = deepClone(obj[key]);
		}
	}
	return clone;
}

// 解构对象key
export const deObjectKey = (obj, keys, reverse = false) => {
	let newObj = {};
	Object.keys(obj).forEach((key) => {
		let bol = keys.includes(key)
		if (reverse ? !bol : bol) {
			newObj[key] = obj[key];
		}
	});
	return newObj;
}


// #ifdef APP-PLUS
// app震动反馈
export function onFeedTap() {
	let platform = uni.getSystemInfoSync().platform
	// #ifdef APP-PLUS
	if (platform == "ios") {
		let UIImpactFeedbackGenerator = plus.ios.importClass('UIImpactFeedbackGenerator');
		let impact = new UIImpactFeedbackGenerator();
		impact.prepare();
		impact.init(1);
		impact.impactOccurred();
	}
	if (platform == "android") {
		uni.vibrateShort();
	}
	// #endif
}
// #endif

// 提取固定字符
export function extractString(str, regex) {
	const match = str.match(regex);
	return match ? match[0] : '';
}

// 将第一个字符转为小写
export function strFirstLetter(str) {
	return str.replace(/\b[a-z]/, function(char) {
		return char.toUpperCase();
	});
}

// 下载文件
export function downloadFile(url, option) {
	return new Promise((resolve, reject) => {
		uni.downloadFile({
			url,
			...option,
			success: function(res) {
				resolve(res);
			},
			fail: function(err) {
				reject(err);
				console.error('文件下载失败', err);
			}
		});
	});
}

// 获取对象深层属性
export function getObjDeepProps(obj, name) {
	const keys = name.split('.');
	let target = obj;
	for (let i = 0; i < keys.length; i++) {
		if (target.hasOwnProperty(keys[i])) {
			target = target[keys[i]];
		} else {
			target[keys[i]] = {};
		}
	}
	return target;
}

// 预览图片
export function previewImage(urls, current = 0, options) {
	uni.previewImage({
		urls,
		current,
		...options
	});
}

export function isVideoFileType(filename) {
	// 正则表达式，匹配常见的视频文件扩展名  
	const videoRegex = /\.(mp4|avi|mov|mkv|webm)$/i;

	// 测试文件名是否匹配正则表达式  
	return videoRegex.test(filename);
}
export function isImageType(extension) {
	const imageRegex = /\.(jpg|jpeg|png|gif|bmp|webp|svg)$/i;
	return imageRegex.test(extension);
}

// #ifdef APP-PLUS
// 保存base64图片文件
export function saveBaseImgFile(base64) {
	return new Promise((resolve, reject) => {
		const bitmap = new plus.nativeObj.Bitmap('base64')
		bitmap.loadBase64Data(base64, () => {
				const url = '_doc/' + new Date().getTime() + '.png'
				bitmap.save(
					url, {
						overwrite: true // 是否覆盖  
						// quality: 'quality'  // 图片清晰度  
					},
					(i) => {
						saveImage(url).then(res => {
							resolve(res);
							bitmap.clear();
						}).catch(e => {
							reject(e);
						});
					},
					(e) => {
						reject(e);
						bitmap.clear()
					}
				)
			},
			(e) => {
				reject(e);
				bitmap.clear()
			}
		)
	})
}
// #endif

// 打开模态框
export function showModal(content, option) {
	return new Promise((resovle, reject) => {
		uni.showModal({
			content,
			...option,
			success: res => {
				if (res.confirm) {
					resovle()
				} else {
					reject();
				}
			}
		})
	});
}

// 对象扁平化
export const objFlat = (obj) => {
	let newObj = {};
	const recursion = (o) => {
		Object.keys(o).forEach(key => {
			const value = o[key];
			if (Object.keys(value).length) {
				recursion(value)
			} else {
				newObj[key] = value;
			}
		});
	}
	recursion(obj);
	return newObj;
}